package com.alfayun.fiscalriskanalysis.systemlogs;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SystemLogsService {

	@Autowired
	private SystemLogsRepository repository;

	public List<SystemLogs> transactionList(String period, String[] type, String[] status) {
		List<Type> typeList = List.of(Type.PURCHASE, Type.BONUS, Type.WITHDRAW);
		List<Status> statusList = List.of(Status.PENDING_PAYMENT, Status.PROCESSING, Status.FNISHED, Status.CANCELED);
		if (type != null && type.length > 0) {
			typeList = Arrays.stream(type).map(item -> Type.valueOf(item)).collect(Collectors.toList());
		}
		if (status != null && status.length > 0) {
			statusList = Arrays.stream(status).map(item -> Status.valueOf(item)).collect(Collectors.toList());
		}
		return repository.findByTypeAndStatusAndCreateTime(typeList, statusList, generateStartTime(period), Instant.now());
	}

	private Instant generateStartTime(String period) {
		Instant startTime = Instant.MIN;
		switch (period) {
		case "oneWeek":
			startTime = Instant.now().minus(7, ChronoUnit.DAYS);
			break;
			
		case "oneMonth":
			startTime = Instant.now().minus(30, ChronoUnit.DAYS);
			break;
			
		case "threeMonth":
			startTime = Instant.now().minus(90, ChronoUnit.DAYS);
			break;
			
		case "halfYear":
			startTime = Instant.now().minus(183, ChronoUnit.DAYS);
			break;
			
		case "oneYear":
			startTime = Instant.now().minus(365, ChronoUnit.DAYS);
			break;

		default:
			break;
		}
		return startTime;
	}

}
